//
//  PlayerPresentaionViewController.m
//  MJAVFoundationDemo
//
//  Created by apple on 16/9/12.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "PlayerPresentaionViewController.h"
#import <MediaPlayer/MediaPlayer.h>
@interface PlayerPresentaionViewController ()<AVAudioPlayerDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSString *_songName;//保存歌名的
    NSInteger _index;//保存滑动到某一行
    NSMutableDictionary *dict;
}

@property(nonatomic,strong)NSTimer *timer;
@end

@implementation PlayerPresentaionViewController
//将这个视图控制器变成单例，无论从什么时候获取它它都是同一个对象，不会被重复创建，一直持有它，这就是为什么点击同一首歌进来时仍然是这个界面而没有被销毁
+ (instancetype)SharedPlayer
{
    static PlayerPresentaionViewController *shared_manager = nil;
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        shared_manager = [[self alloc] init];
    });
    return shared_manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor=[UIColor whiteColor];
    //设置图片歌名和歌手
   
    //设置滑块图片
    UIImage *image=[UIImage imageNamed:@"process_thumb"];    
    [self.slider setThumbImage:image forState:UIControlStateNormal];
    
    //设置显示歌词的表的一些属性,刚开始进来让歌词隐藏
    self.LricTable.hidden=YES;
    //让表格没有分割线
    self.LricTable.separatorStyle=UITableViewCellSeparatorStyleNone;
    //让表格的背景为一张图片
    UIImageView *backImageView=[[UIImageView alloc]initWithFrame:self.LricTable.bounds];
    [backImageView setImage:[UIImage imageNamed:@"lricImage"]];
    self.LricTable.backgroundView=backImageView;
   
}


#pragma mark--表的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _lricArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"reuseCell"];
    if (!cell)
    {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseCell"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.backgroundColor=[UIColor clearColor];
        cell.opaque=YES;
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(5, 0, KWIDTH-10, 28)];
        label.tag=100;
        label.font=[UIFont systemFontOfSize:15];
        label.backgroundColor=[UIColor clearColor];
        label.opaque=YES;
        label.textColor=[UIColor whiteColor];
        label.adjustsFontSizeToFitWidth=YES;
        label.textAlignment=NSTextAlignmentCenter;
        [cell.contentView addSubview:label];
    }
    UILabel *lbl=[cell.contentView viewWithTag:100];
    if (_index==indexPath.row) {
        lbl.font=[UIFont systemFontOfSize:19];
    }else
    {
        lbl.font=[UIFont systemFontOfSize:15];
    }
    NSString *str=_lricArray[indexPath.row];
    lbl.text=str;
    return cell;
}


#pragma mark--初始化定时器
-(NSTimer *)timer
{
    if (!_timer)
    {
        _timer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    }
    return _timer;
}


#pragma mark--更新进度条
-(void)updateProgress
{
    //设置滑动滑动的位置=音乐当前播放时间/音乐总时间  （单位是秒）
    float progress=_audioPlayer.currentTime/_audioPlayer.duration;
    
    //改变进度条时，后台控制板进度条也应该改变
    [dict setObject:[NSNumber numberWithDouble:self.audioPlayer.currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    //        设置锁屏状态下屏幕显示播放音乐信息,MPNowPlayingInfoCenter会将信息传递给控制面板
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    
    //duration是以秒计算，歌曲总时间
   //currentTime 当前播放到哪个时间
    //滑动条的值是0~1
    
    //获得当前播放时间的分和秒
    NSInteger minute=_audioPlayer.currentTime/60;
    NSInteger second=_audioPlayer.currentTime-(minute*60);
    NSString *secondStr;
    
    if (second<10)
    {
        secondStr=[NSString stringWithFormat:@"%@%zd",@"0",second];
    }else
    {
        secondStr=[NSString stringWithFormat:@"%zd",second];
    }
   
    self.currentLbl.text=[NSString stringWithFormat:@"%zd:%@",minute,secondStr];
    self.slider.value=progress;
    for (NSNumber *timeNumber in _timeArray)
    {
         NSString *currrentString=[NSString stringWithFormat:@"%f",_audioPlayer.duration*progress];
       //当歌词的时间与当前播放时间一致，则让表滑到这句歌词所在的一行，并且这一行一直都垂直居中
        if (timeNumber.integerValue==currrentString.integerValue)
        {
            _index=[_timeArray indexOfObject:timeNumber];
            
            if (_index>0 && _index<_lricArray.count)
            {
                //刷新表改变字体大小
                 [self.LricTable reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:_index inSection:0],[NSIndexPath indexPathForRow:_index-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            }
            [self.LricTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_index inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        }
    }
   

}

#pragma mark--自动更换下一首，这是AVAudioPlayer的代理方法
-(void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
   if (flag)
   {
    
       //只要设置_songIndex就能切换歌曲
       //顺序播放只要+1，随机播放就将_songIndex改成一个随机数，这个随机数最大值不能超过音乐库总数量-1，
       if (_songIndex<_allSongsDataArray.count-1) {
           _songIndex++;
         [self changeSong];
           [[NSNotificationCenter defaultCenter]postNotificationName:@"changeBorder" object:@(_songIndex)];
       }else
       {
           [MBProgressHUD showError:@"已经最后一首了"];
       }
   }

}
#pragma mark--设置数据，每次换歌时都要同步切换图片歌词神马的
-(void)setData
{
    MusicPlayerModel *model=_allSongsDataArray[_songIndex];
    self.bgImage.image=[UIImage imageNamed:model.bgImageName];
    self.singerNameLbl.text=model.singerName;
    self.songNameLbl.text=model.musicName;
    _lricArray=model.lrcsArray;
    _timeArray=model.lrcTimeArray;
    [self.LricTable reloadData];
}
#pragma mark--更换上一首或下一首需要切换记录歌曲索引
-(void)changeSongWithIsNext:(BOOL)isNext
{
    NSLog(@"Fram=%zd",_songIndex);
    if (isNext)
    {
        if (_songIndex<_allSongsDataArray.count-1)
        {
            _songIndex++;

        }else
        {
            [MBProgressHUD showError:@"已经是最后一首了"];
            return;
        }
    }else
    {
        if (_songIndex>0) {
            _songIndex--;
            
        }else
        {
            [MBProgressHUD showError:@"前面没有可播放的歌曲了"];
            return;
        }
    }
    [self changeSong];
    //发个通知让前一个歌曲列表视图更换那个歌曲正在播放
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeBorder" object:@(_songIndex)];
    
}
#pragma mark--换新歌曲的时候要执行的，每次重新初始化AVAudioPlayer
-(void)changeSong
{
    NSLog(@"to=%zd",_songIndex);
    if (_audioPlayer) {
        [_audioPlayer stop];
        _audioPlayer = nil;
    }
    MusicPlayerModel *model=_allSongsDataArray[_songIndex];
    _songName=model.musicName;
    NSString *filePath=[[NSBundle mainBundle]pathForResource:model.musicName ofType:@"mp3"];
    NSError *error;
    // 要先在退出后播放，那必须要设置以下：
    //1.----Info.plist.添加一行 Required background modes，在其下加入app plays audio  如下图，这个意思就是说，你要后台播放一个音频。
   //2.---引入AVFoundation framework动态库后，通过以下代码注册后台播放：
    [[AVAudioSession  sharedInstance] setCategory: AVAudioSessionCategoryPlayback  error: nil];
    NSError *activationError = nil;
    
    [[AVAudioSession  sharedInstance] setActive: YES   error: &activationError];
    
    if (activationError)
    {
        
        NSLog(@"activ error");
        
    }
    //2.---在ViewWillAppear和viewWillDisappear里面设置应用进入后台时成为第一响应，这个不设置在锁屏后的控制面板看不到音乐控制
    //3.---重写父类方法- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent实现对控制面板上播放暂停上一首下一首的控制，不然点击按钮没反应
    //4.----#import <MediaPlayer/MediaPlayer.h>，在音乐播放的时候设置-(void)configNowPlayingInfoCenter实现锁屏的时候显示专辑名、封面等等信息，MPNowPlayingInfoCenter会帮你传递这些信息，你只负责赋值就好了
    
    
    //初始化播放器并设置它的播放文件路径
    _audioPlayer=[[AVAudioPlayer alloc]initWithData:[NSData dataWithContentsOfFile:filePath] error:&error];
    _audioPlayer.delegate = self;
    [_audioPlayer play];
    [self configNowPlayingInfoCenter];

    if (error) {
        NSLog(@"错误信息：%@",error.localizedDescription);
                }
    
    NSInteger minute=_audioPlayer.duration/60;
    NSInteger second=_audioPlayer.duration-(minute*60);
    self.totalTimeLbl.text=[NSString stringWithFormat:@"%zd:%zd",minute,second];
    [self setData];
}

#pragma mark--显示歌词
- (IBAction)clickOnChangeLrc:(id)sender
{
    UIButton *btn=(UIButton *)sender;
    if (!btn.isSelected)
    {
        btn.selected=YES;
        self.LricTable.hidden=NO;
    }else
    {
        btn.selected=NO;
        self.LricTable.hidden=YES;

    }

}
#pragma mark--上一首
- (IBAction)clickOnPrevious:(id)sender
{
    [self changeSongWithIsNext:NO];
}
#pragma mark--下一首
- (IBAction)clickOnNext:(id)sender
{

    [self changeSongWithIsNext:YES];
   
}
#pragma mark--播放或暂停控制按钮
- (IBAction)clickOnPlay:(id)sender
{
    UIButton *btn=(UIButton *)sender;
    //如果正在播放就暂停
    if (self.audioPlayer.isPlaying)
    {
        [self pause];
        btn.selected=YES;
    }
    //否则就播放
    else
    {
        [self play];
        btn.selected=NO;
    }
    
}
#pragma mark--让播放器播放
-(void)play
{
    [self.audioPlayer play];
}
#pragma mark--让播放器暂停
-(void)pause
{
    [self.audioPlayer pause];
}

#pragma mark--滑动进度条控制音乐
- (IBAction)sliderMove:(id)sender
{
    //当前播放时间=滑块移动的位置*音乐总时间，这个公式跟上面的计算播放进度一致
    self.audioPlayer.currentTime=self.slider.value*self.audioPlayer.duration;
}
#pragma mark--返回上一个界面
- (IBAction)ClickOnCloseView:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark--重写父类方法实现对控制面板的控制
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    if (receivedEvent.type == UIEventTypeRemoteControl)
    {
        UIButton *previousBtn=[self.view viewWithTag:400];
        UIButton *pauseOrPlayBtn=[self.view viewWithTag:500];
        UIButton *nextBtn=[self.view viewWithTag:600];
   //在控制面板对应的按钮事件里分别调用本类中的方法
        switch (receivedEvent.subtype)
        {
                
            case UIEventSubtypeRemoteControlTogglePlayPause:
            {
                //暂停
                [self clickOnPlay:pauseOrPlayBtn];
            }
                break;
                
            case UIEventSubtypeRemoteControlPreviousTrack:
            {
                //上一首
                [self clickOnPrevious:previousBtn];
            }
                break;
                
            case UIEventSubtypeRemoteControlNextTrack:
            {
             //下一首
                [self clickOnNext:nextBtn];
            }
                break;
                
            case UIEventSubtypeRemoteControlPlay:
            {
            //播放
                [self clickOnPlay:pauseOrPlayBtn];

            }
                break;
                
            case UIEventSubtypeRemoteControlPause:

            {
               //暂停
                [self clickOnPlay:pauseOrPlayBtn];

            }break;
                
            default:
                break;
        }
    }
}
#pragma mark--实现锁屏状态，显示的歌曲信息

-(void)configNowPlayingInfoCenter{
    if (NSClassFromString(@"MPNowPlayingInfoCenter")) {
        MusicPlayerModel *model=_allSongsDataArray[_songIndex];
        dict = [[NSMutableDictionary alloc] init];
        
        //歌曲名称
        [dict setObject:model.musicName forKey:MPMediaItemPropertyTitle];
        
        //演唱者
        [dict setObject:model.singerName forKey:MPMediaItemPropertyArtist];
        
        [dict setObject:@"KMJ--AVFoundationDemo" forKey:MPMediaItemPropertyAlbumTitle];
        //专辑名
       // forKey:MPMediaItemPropertyAlbumTitle;
        
        //专辑缩略图
        UIImage *image = [UIImage imageNamed:model.bgImageName];
    
        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
        [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
        
        //音乐总时长
        [dict setObject:[NSNumber numberWithDouble:self.audioPlayer.duration] forKey:MPMediaItemPropertyPlaybackDuration];
        
       // 音乐当前播放时间 在计时器中修改
        [dict setObject:[NSNumber numberWithDouble:self.audioPlayer.currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
       // 设置锁屏状态下屏幕显示播放音乐信息,MPNowPlayingInfoCenter会将信息传递给控制面板

        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=YES;
    MusicPlayerModel *model=_allSongsDataArray[_songIndex];
    if (![_song isEqualToString:_songName])
    {
        _songName=model.musicName;
        self.timer.fireDate=[NSDate date];
        //开启播放器
        [self changeSong];
    }
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden=NO;
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}
- (BOOL)canBecomeFirstResponder
{
    return YES;
}
@end
